#include "listen_deserialize.h"

const int ListenDeserialize::n_key      	= 12;
const int ListenDeserialize::MAX_BUFF_SIZE 	= 100;
const char ListenDeserialize::key[][20] 	= {
	"OJ", "Status Code", "Status", "Run ID", "Submit Time", "User", 
	"Problem", "Result", "Language", "Memory", "Time", "Code Length"
};

EpollData* ListenDeserialize::operator() (const char *stream) {
	int socket_fd = 0;
	int i, j, index = 0;

	while (true) {
		if (stream[index] == '|') {
			index++;
			break;
		}
		socket_fd = socket_fd * 10 + stream[index] - '0';
		index++;
	}
		
	char *buff;
	std::vector<char *> value;
	for (i = 0; i < n_key; i++) {
		buff = new char[MAX_BUFF_SIZE];
		if (i != n_key - 1) {
			for (j = 0; true; j++, index++) {
				if (stream[index] == '|') {
					index++;
					buff[j] = '\0';
					break;
				}
				buff[j] = stream[index];
			}
		}
		else {
			strcpy(buff, stream+index);
		}
		value.push_back(buff);
	}
	std::string json = create_json_str(value);
	char length[16];
	sprintf(length, "%d", json.length());
	printf("listen_deserialize: %s %s\n", length, json.data());
	return new EpollData(SOCKET_SEND_TYPE, socket_fd, new SocketSendBuff(length, json.data()));
}


std::string ListenDeserialize::create_json_str(std::vector<char *> &value) {
	std::string json = "{";
	char item[MAX_BUFF_SIZE];
	for (int i = 0; i < n_key; i++) {
		sprintf(item, "\"%s\":\"%s\"", key[i], value[i]);
		json += std::string(item);
		if (i != n_key - 1) json += ",";
		else json += "}";
	}
	return json;
}

